package com.gxd.dao.impl;

import com.gxd.dao.GoodsDao;
import com.gxd.domain.Goods;
import com.gxd.util.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.awt.print.Book;
import java.sql.SQLException;
import java.util.List;

public class GoodsDaoImpl implements GoodsDao {
    QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
    @Override
    public long selectCount(int typeId) {
        String sql=" select count(0) from tb_goods where typeId=? ";
        try {
            long count = (long) queryRunner.query(sql, new ScalarHandler(), typeId);
            return count;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Goods> selectData(int typeId, int starIndex, int page_size) {
        String sql=" select * from tb_goods where typeId=? limit ?,?  ";
        try {
            List<Goods> list =queryRunner.query(sql, new BeanListHandler<>(Goods.class), typeId,starIndex,page_size);
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Goods findGoodById(int id) {

        String sql=" select id,name,pubdate,picture,price,star,intro,typeid from tb_goods where id=?  ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(Goods.class),id);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public long selectCount() {

        String sql=" select count(0) from tb_goods";
        try {
            long count = (long) queryRunner.query(sql, new ScalarHandler());
            return count;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<Goods> selectByPage(int page_num, int page_size) {
        try {
            String sql="select * from tb_goods limit ?,? ";

            return queryRunner.query(sql,new BeanListHandler<>(Goods.class),(page_num-1)*page_size,page_size);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public void addGoods(Goods goods) {
        String sql=" insert into tb_goods values (null,?,?,?,?,?,?,?) ";
        Object[] params={goods.getName(),goods.getPubdate(),goods.getPicture(),goods.getPrice(),goods.getStar(),goods.getIntro(),goods.getTypeid()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
